package demo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.yaml.snakeyaml.Yaml;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.core.Path;
import com.jfinal.upload.UploadFile;


	@Path("/book")
    public class BookController extends Controller {
        public void index() throws IOException {
        	String bookname=get("name");
        	
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filepath = path+"/"+bookname+"/"+bookname+".txt";
        	//File file=new File(filepath);
        	
            InputStream inputStream = new FileInputStream(filepath);
            //String content = readContentFromInputStream(inputStream);
            
            StringBuilder content = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
                content.append("<br>");
            }
            reader.close();
            inputStream.close();
            setAttr("book", content);
            setAttr("name", bookname);
        	render("book.html");
           
        }
        //新增标签
        public void createsq() throws IOException {
        	
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String time=jo.getString("time");
        	String remark=jo.getString("remark");
        	String biaoqian=jo.getString("biaoqian");
        	String biaoqianid=jo.getString("biaoqianid");
        	String rangest=jo.getString("range");
        	String content=jo.getString("content");
        	String bookname=jo.getString("bookname").trim();
        	
        	
        	//byte[] decodedBytes = Base64.getDecoder().decode(content);
            //String decodedString = new String(decodedBytes);
        	if(rangest==null){rangest="";}
        	if(remark==null){remark="";}
        	if(biaoqian==null){biaoqian="";}
        	if(biaoqianid==null){biaoqianid="";}
        	
        	////////////////设置content
        	
        	String str = new String("书签".getBytes("gbk"), "utf-8");
        	
        	String start="\"getsq("+time+",'"+bookname+"')\">"+str+"</span>----&gt;</div>";
			String end="<div id=\""+time+"_1\"";
			rangest=content.substring(content.indexOf(start)+start.length(), content.indexOf(end));
			//System.out.println(start);
			//System.out.println("**************************************");
			//System.out.println(rangest);
        	////////////////
        	
        	rangest = rangest.replace("\r", "@r@").replace("\n", "@n@").replace("'", "‘").replace("\"", "“").replace("(", "（").replace(")", "）").replace("[", "【").replace("]", "】").replace(".", "。").replace("{", "【").replace("}", "】");
        	//System.out.println(rangest);
        	resetbook(bookname,content);
        	setsuoyin(bookname,time,rangest,remark,biaoqian,biaoqianid);
        	
        	render("book.html");
        }
        
      //新增标签
        public void createimg() throws IOException {
        	
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String time=jo.getString("time");
        	String remark=jo.getString("remark");
        	
        	String content=jo.getString("content");
        	String bookname=jo.getString("bookname").trim();
        	
        	
        	//byte[] decodedBytes = Base64.getDecoder().decode(content);
            //String decodedString = new String(decodedBytes);
        	
        	if(remark==null){remark="";}
        	resetbook(bookname,content);
        	setimg(bookname,time,remark);
        	render("book.html");
        }
        
      //编辑img
        public void editimg() throws IOException {
        	UploadFile uploadFile = getFile("file");
        	File file=null;
        	String renameFileName="";
        	String type="";
        	if(uploadFile!=null){
        		file = uploadFile.getFile();
        		renameFileName = file.getName().trim();
        		type=renameFileName.substring(renameFileName.lastIndexOf("."), renameFileName.length());
        	}
    	     
        	String time=get("time");
        	String remark=get("remark");
        	String bookname=get("bookname").trim();
        	if(remark==null){
        		remark="";
        	}
        	//String jsonData = getRawData();
        	//remark = URLDecoder.decode(remark, "UTF-8");
        	//JSONObject jo = JSONObject.parseObject(jsonData);
        	//String time=jo.getString("time");
        	//String remark=jo.getString("remark");
        	//String bookname=jo.getString("bookname").trim();
        	remark = remark.replace("\r", "@r@").replace("\n", "@n@").replace("'", "‘").replace("\"", "“").replace("(", "（").replace(")", "）").replace("[", "【").replace("]", "】").replace(".", "。").replace("{", "【").replace("}", "】");
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_img.txt";
        	
        	String fileContent = readFile(filePath);
            String startString = "@@##@@"+time;
            String endString = time+"@@##@@";
            int startIndex = fileContent.indexOf(startString);
            int endIndex = fileContent.lastIndexOf(endString);
            String result = fileContent.substring(startIndex + startString.length(), endIndex);
            JSONObject re=(JSONObject) JSONObject.parse(result);
            re.put("remark", remark);
            String oldtype=re.getString("type");
            if(oldtype==null){
            	oldtype=".png";
            }
            if(uploadFile!=null){
            	re.put("type", type);
            }
            
            String est=startString+re.toJSONString()+endString;
            
            String start=fileContent.substring(0,fileContent.indexOf("@@##@@"+time));
        	String end=fileContent.substring(fileContent.indexOf(time+"@@##@@")+time.length()+6,fileContent.length());
            String st=start+est+end;
            
            //
            FileOutputStream outputStream = new FileOutputStream(filePath);
            OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
            writer.write(st);
            writer.flush();
            writer.close();
            outputStream.close();
            if(uploadFile!=null){
            	File f=new File(path+"/"+bookname+"/"+time+oldtype);
            	if(f.exists()){
            		f.delete();
            	}
            	file.renameTo(new File(path+"/"+bookname+"/"+time+type)); 
            }
            
            renderJson((JSONObject) JSONObject.parse("{'res':'ok'}"));
        	
        }
        
        //编辑标签
        public void editsq() throws IOException {
        	
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String time=jo.getString("time");
        	String remark=jo.getString("remark");
        	String ids=jo.getString("id");
        	String names=jo.getString("name");
        	String bookname=jo.getString("bookname").trim();
        	remark = remark.replace("\r", "@r@").replace("\n", "@n@").replace("'", "‘").replace("\"", "“").replace("(", "（").replace(")", "）").replace("[", "【").replace("]", "】").replace(".", "。").replace("{", "【").replace("}", "】");
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_bq.txt";
        	
        	String fileContent = readFile(filePath);
            String startString = "@@##@@"+time;
            String endString = time+"@@##@@";
            int startIndex = fileContent.indexOf(startString);
            int endIndex = fileContent.lastIndexOf(endString);
            String result = fileContent.substring(startIndex + startString.length(), endIndex);
            JSONObject re=(JSONObject) JSONObject.parse(result);
            re.put("remark", remark);
            re.put("bq", names);
            re.put("bqid", ids);
            re.put("bookname", bookname);
            re.put("id", time);
            String est=startString+re.toJSONString()+endString;
            
            String start=fileContent.substring(0,fileContent.indexOf("@@##@@"+time));
        	String end=fileContent.substring(fileContent.indexOf(time+"@@##@@")+time.length()+6,fileContent.length());
            String st=start+est+end;
            
            //
            FileOutputStream outputStream = new FileOutputStream(filePath);
            OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
            writer.write(st);
            writer.flush();
            writer.close();
            outputStream.close();
            
            renderJson((JSONObject) JSONObject.parse("{'res':'ok'}"));
        	
        }
        
        //鼠标滑过图片
        public void getimg() throws IOException{
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String time=jo.getString("time");
        	String bookname=jo.getString("bookname").trim();
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_img.txt";
        	
        	String fileContent = readFile(filePath);
            String startString = "@@##@@"+time;
            String endString = time+"@@##@@";

            int startIndex = fileContent.indexOf(startString);
            int endIndex = fileContent.lastIndexOf(endString);

            String result = fileContent.substring(startIndex + startString.length(), endIndex);
            JSONObject re=(JSONObject) JSONObject.parse(result);
            renderJson(re);
        }
        
        //鼠标滑过
        public void getsq() throws IOException{
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String time=jo.getString("time");
        	String bookname="";
        	try{
        	    bookname=jo.getString("bookname").trim();
        	}catch(Exception e){
        		bookname="倪海厦人纪系列之《神农本草经》";
        	}
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_bq.txt";
        	
        	String fileContent = readFile(filePath);
            String startString = "@@##@@"+time;
            String endString = time+"@@##@@";

            int startIndex = fileContent.indexOf(startString);
            int endIndex = fileContent.lastIndexOf(endString);

            String result = fileContent.substring(startIndex + startString.length(), endIndex);
            JSONObject re=(JSONObject) JSONObject.parse(result);
            renderJson(re);
        }
        
      //删除标签
        public void deleimg() throws IOException{
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String imgid=jo.getString("imgid");
        	String content=jo.getString("content");
        	String bookname=jo.getString("bookname").trim();
        	String imgname=jo.getString("imgname");
        	
        	parseimg(bookname,imgid,imgname);
        	resetbook(bookname,content);
        	renderJson((JSONObject) JSONObject.parse("{'res':'ok'}"));
        }
        
        //删除标签
        public void delesq() throws IOException{
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String bqid=jo.getString("bqid");
        	String content=jo.getString("content");
        	String bookname=jo.getString("bookname").trim();
        	
        	parse(bookname,bqid);
        	resetbook(bookname,content);
        	renderJson((JSONObject) JSONObject.parse("{'res':'ok'}"));
        }
        
        private static String readFile(String filepath) throws IOException {
            StringBuilder fileContent = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filepath),"utf-8"));
           
            String line = reader.readLine();
            while (line != null) {
                fileContent.append(line);
                line = reader.readLine();
            }
            reader.close();
            return fileContent.toString();
        }
        
        //查询药物
        public void getyao() throws IOException{
        	String jsonData = getRawData();
        	jsonData = URLDecoder.decode(jsonData, "UTF-8");
        	JSONObject jo = JSONObject.parseObject(jsonData);
        	String yao=jo.getString("yao").trim();
        	if(!yao.equals("")){
        		String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        		File folder = new File(path);
        		JSONArray ja=new JSONArray();
        		traverse(folder,path,ja,yao);
        		if(ja.size()>0){
        			renderJson((JSONObject) JSONObject.parse("{'res':'ok','data':"+ja.toJSONString()+"}"));
        		}else{
        			renderJson((JSONObject) JSONObject.parse("{'res':'nodata'}"));
        		}
        		
        	}else{
        		renderJson((JSONObject) JSONObject.parse("{'res':'nok'}"));
        	}
        }
        
        
        private void traverse(File folder,String path,JSONArray ja,String yao) throws IOException {
    	    
            if (folder.isDirectory()) {
                File[] files = folder.listFiles();
                for (File file : files) {
                    traverse(file,path,ja,yao);
                }
            } else {
            	String allname=folder.getName();
            	if(allname.endsWith("_bq.txt")){
            		String bookname=allname.substring(0, allname.length()-7);
            		String filePath=path+"/"+bookname+"/"+bookname+"_bq.txt";
                	
                	String fileContent = readFile(filePath);
                	Pattern pattern = Pattern.compile("\\{([^}]*)\\}");
                    Matcher matcher = pattern.matcher(fileContent);
                    while (matcher.find()) {
                    	String findst=matcher.group();
                        JSONObject jo=JSONObject.parseObject(findst);
                        jo.put("bookname", bookname);
                        //////////////////////////////////////////////////remark
                        String remark=jo.getString("remark").trim();
                        if(remark.contains("@n@")){
                        	remark=remark.substring(0, remark.indexOf("@n@"));
                        }
                        String[] rkja=remark.split(" ");
                        for (String s : rkja) {
                         	if(s.equals(yao)){
                         		ja.add(jo);
                         		break;
                         	}
                         }
                        
                    }
                    
            	}
                
            }
        }
        
        private String readContentFromInputStream(InputStream inputStream) {
    	    StringBuilder sb = new StringBuilder();
    	    try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
    	        String line;
    	        while ((line = reader.readLine()) != null) {
    	            sb.append(line);
    	            sb.append("<br>");
    	        }
    	    } catch (IOException e) {
    	        e.printStackTrace();
    	    }
    	    return sb.toString();
    	}
        
        //
        public void parseimg(String bookname,String time,String imgname) throws IOException {
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_img.txt";
        	System.out.println(filePath);
            File sourceFile = new File(filePath);
            File tempFile = File.createTempFile("temp", ".txt"); 
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile),"UTF-8"));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile),"UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                //if (!line.matches("@@##@@"+time+".*"+time+"@@##@@")) {
                //    writer.write(line);
                //}
            	String start=line.substring(0,line.indexOf("@@##@@"+time));
            	String end=line.substring(line.indexOf(time+"@@##@@")+time.length()+6,line.length());
            	
            	writer.write(start+end);
            }
            writer.flush();
            reader.close();
            writer.close();
            sourceFile.delete();
            tempFile.renameTo(new File(sourceFile.getAbsolutePath())); 
            String imgPath=path+"/"+bookname+"/"+imgname;
            new File(imgPath).delete();
        }
        
        //
        public void parse(String bookname,String time) throws IOException {
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_bq.txt";
        	System.out.println(filePath);
            File sourceFile = new File(filePath);
            File tempFile = File.createTempFile("temp", ".txt"); 
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile),"UTF-8"));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile),"UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                //if (!line.matches("@@##@@"+time+".*"+time+"@@##@@")) {
                //    writer.write(line);
                //}
            	String start=line.substring(0,line.indexOf("@@##@@"+time));
            	String end=line.substring(line.indexOf(time+"@@##@@")+time.length()+6,line.length());
            	
            	writer.write(start+end);
            }
            writer.flush();
            reader.close();
            writer.close();
            sourceFile.delete();
            tempFile.renameTo(new File(sourceFile.getAbsolutePath())); 
        }
        
        //设置索引
        private void setsuoyin(String bookname,String time,String content,String remark,String biaoqian,String biaoqianid){
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_bq.txt";
        	File file = new File(filePath);

            if(!file.exists()) {
            	try {
                    file.createNewFile();
                   
                } catch (IOException e) {
                   
                    return;
                }
            } 
            
            try {
                //FileWriter writer = new FileWriter(filePath, true);
            	OutputStreamWriter writerStream = new OutputStreamWriter(new FileOutputStream(filePath,true),"UTF-8");
                //BufferedWriter buffer = new BufferedWriter(writerStream);
            	writerStream.write("@@##@@"+time+"{'content': '"+content+"', 'remark': '"+remark+"', 'bq': '"+biaoqian+"', 'bqid': '"+biaoqianid+"','id':'"+time+"','bookname':'"+bookname+"'}"+time+"@@##@@" );
            	writerStream.flush();
                //buffer.close();
                writerStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        //设置图片
        private void setimg(String bookname,String time,String remark){
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+"_img.txt";
        	File file = new File(filePath);

            if(!file.exists()) {
            	try {
                    file.createNewFile();
                   
                } catch (IOException e) {
                   
                    return;
                }
            } 
            
            try {
                //FileWriter writer = new FileWriter(filePath, true);
            	OutputStreamWriter writerStream = new OutputStreamWriter(new FileOutputStream(filePath,true),"UTF-8");
                //BufferedWriter buffer = new BufferedWriter(writerStream);
            	writerStream.write("@@##@@"+time+"{'remark': '"+remark+"','type':'.png','id':'"+time+"','bookname':'"+bookname+"'}"+time+"@@##@@" );
            	writerStream.flush();
                //buffer.close();
                writerStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        //覆盖书籍
        private void resetbook(String bookname,String content) throws IOException{
        	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
        	String filePath=path+"/"+bookname+"/"+bookname+".txt";
        	
              
              FileOutputStream outputStream = new FileOutputStream(filePath);
              OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
              writer.write(content);
              writer.flush();
              writer.close();
              outputStream.close();
             
            
            
        }
    }
	
	

